# -*- coding: utf-8 -*-
from city_code import CITY
from util import city_code

import urllib2,string,json
from urllib import urlencode

import hmac
import hashlib
import base64

appid = "c11794790cc577de"
private_key = "3fe2cd_SmartWeatherAPI_00a89ba"

def city_code(city_name):
    if city_name in  CITY:
        return CITY.get(city_name)
    else:
        return None
    
def get_city_name(city):

    if "tq" in city:
        city = city.replace('tq','').replace('+','').strip()
        if len(city)>0:
            return city
        else:
            return None
    else:
        return None
    
def city_weather(city):
    city_name = get_city_name(city)
    if city_name:
#         code = city_code(city_name)
#         if code:
        url = "http://apistore.baidu.com/microservice/weather?cityname=%s" % (city_name)
        data = urllib2.urlopen((url)).read()
        jsonDatas = json.loads(data)

        if jsonDatas['errNum'] == 0:
            try:
                city = jsonDatas["retData"]["city"]
                temp = jsonDatas["retData"]["temp"]
                temp1 = jsonDatas["retData"]["l_tmp"]
                temp2 = jsonDatas["retData"]["h_tmp"]
                weather = jsonDatas["retData"]["weather"]
                wd = jsonDatas["retData"]["WD"]
                ws = jsonDatas["retData"]["WS"]
                ptime = jsonDatas["retData"]["time"]

                content = city + "，".decode('utf-8') + \
                        weather + '，'.decode('utf-8')  + wd + ws + \
                        "，实时气温：".decode('utf-8') + \
                        temp + "℃，最高气温：".decode('utf-8') + \
                        temp2 + "℃，最低气温：".decode('utf-8') + temp1 + \
                        "℃，发布时间：".decode('utf-8') + str(ptime)
                
            except (SyntaxError) as err:
                print(">>>>>> SyntaxError: " + err.args)
            except Exception,e:
                print(">>>>>> OtherError: " + e)
            else:
                return content
            finally:
                None
        else:
            return "请输入正确的城市名"
    else:
        return None

if __name__ == '__main__':
#     print city_weather("  tq  +")
#     public_key="http://open.weather.com.cn/data/?areaid=%s&type=%s&date=%s&appid=%s" % ("101020600","forecast_v","201512071010",appid)
#     key = hmac.new(private_key,public_key,hashlib.sha1).digest().encode('base64').rstrip()
#     url = "http://open.weather.com.cn/data/?areaid=%s&type=%s&date=%s&appid=%s&%s" % ("101020600","forecast_v","201512071010",appid[:6],urlencode({'key':key}))
#     print urllib2.urlopen((url)).read()
    print city_weather('tq贵池')